// import { FormatUtils } from '@/utils/formatcommit_data'
// import { NodeUtils } from '@/utils/nodeUtils'
import {optMap} from "./const.js";
import $func from '@/utils/index'
const isEmpty = data => data === null || data === undefined || data === ''
const isEmptyArray = data => Array.isArray(data) ? data.length === 0 : true

export class FormatUtils {
    /**
     * 对基础设置,高级设置等设置页内容进行格式化
     * @param param
     */
    static formatSettings(param) {
        let treeList = this.flattenMapTreeToList(param);
        let combinationList = this.getEndpointNodeId(treeList);
        let finalList = this.cleanNodeList(combinationList);

        return this.adapterActivitiNodeList(finalList);
    }
    /**
    * 展平树结构
    * @param {Object} treeData  - 节点数据
    * @returns Array - 节点数组
    */
    static flattenMapTreeToList(treeData) {
        let nodeData = [];
        function traverse(node) {
            if (node.nodeType === 4) {
                if (node.childNode) {
                    node.childNode.nodeFrom = node.nodeId;
                    traverse(node.childNode);
                }
                if (!isEmptyArray(node.conditionExpressionList)) {
                    for (const child of node.conditionExpressionList) {
                        child.nodeFrom = node.nodeId;
                        traverse(child);
                    }
                    node.nodeToList = node.conditionExpressionList.map(item => item.nodeId);
                    node.nodeTo = node.nodeToList.join(',');
                    delete node.conditionExpressionList
                }
            }
            else if (node.childNode) {
                node.nodeToList = [node.childNode.nodeId];
                node.nodeTo = node.nodeToList.join(',');
                node.childNode.nodeFrom = node.nodeId;
                traverse(node.childNode);
            }
            delete node.childNode
            nodeData.push(node);
        }
        traverse(treeData);
        return nodeData;
    }
    /**
     * 递归处理网关节点下属子节点的nodeToList数据
     * @param { Array } parmData -节点关系数组
     * @returns
     */
    static getEndpointNodeId(parmData) {

        if (isEmptyArray(parmData)) return parmData;

        let getwayList = parmData.filter((c) => {
            return c.nodeType === 4;
        });

        if (isEmptyArray(getwayList)) return parmData;

        let nodesGroup = {};
        for (let t of parmData) {
            if (nodesGroup.hasOwnProperty(t.nodeFrom)) {
                nodesGroup[t.nodeFrom].push(t)
            } else {
                nodesGroup[t.nodeFrom] = [t]
            }
        }
        for (let getway of getwayList) {
            if (nodesGroup.hasOwnProperty(getway.nodeId)) {
                let itemNodes = nodesGroup[getway.nodeId];
                let comNode = itemNodes.find((c) => { return c.nodeType !== 3; });
                if (!comNode) continue;
                let conditionList = itemNodes.filter((c) => { return c.nodeId !== comNode.nodeId; });
                for (let itemNode of conditionList) {
                    function internalTraverse(info) {
                        if (info) {
                            if (!nodesGroup[info.nodeId]) {
                                info.nodeToList = [comNode.nodeId];
                            } else {
                                let tempNode = nodesGroup[info.nodeId];
                                if (Array.isArray(tempNode)) {
                                    for (let t_item of tempNode) {
                                        internalTraverse(t_item);
                                    }
                                }
                                else {
                                    internalTraverse(tempNode);
                                }
                            }
                        }
                    }
                    internalTraverse(itemNode);
                }
            }
        }
        return parmData;
    }
    /**
     * 清理节点数据
     * @param { Array } arr -节点数组
     * @returns
     */
    static cleanNodeList(arr) {
        let nodeIds = arr.map((c) => { return c.nodeId; });
        for (const node of arr) {
            node.nodeToList = Array.from(new Set(node.nodeToList));
            node.nodeTo = node.nodeToList.join(',');
            if (!isEmptyArray(node.nodeToList)) {
                node.nodeToList = node.nodeToList.filter((key) => {
                    return nodeIds.indexOf(key) > -1;
                });
                node.nodeTo = node.nodeToList.join(',');
            }
        }
        return arr;
    }

    /**
     * 格式化node数据，对接api接口
     * @param {Array} nodeList
     * @returns
     */
    static adapterActivitiNodeList(nodeList) {

        for (let node of nodeList) {
            if (node.hasOwnProperty('id')) {
                delete node.id;
            }
            if (node.nodeType === 3) {
                let conditionObj = {
                    conditionList: node.conditionList,
                    sort: node.priorityLevel,
                    isDefault: node.isDefault
                };
                Object.assign(node, { property: {} });
                let conditionExpressionList=[]
                let c = node.conditionList;
                if (c && c.length > 0) {
                    for (let i = 0; i < c.length; i++) {
                        let item = c[i];
                        let hm = typeof item.value ==='string'  ? `'${item.value}'` : item.value;
                        conditionExpressionList.push({
                            fieldCode:item.columnId,
                            fullExpression:`${item.columnId} ${optMap[item.optType]} ${hm}`
                        })
                    }
                }
                node.conditionExpressionList=conditionExpressionList
                node.property = conditionObj;
                node.nodeObj=JSON.stringify(conditionObj)
                delete node.conditionList;
            }

            //  //1-指定成员，4-部门负责人，6-标签，8-申请人本人，9-申请人自选
            //         approvalUserType:"1",
            //         //approvalParams 根据approvalUserType选择的类型来，指定部门负责人,指定成员：传用户id；标签：传标签id，其他类型传空值即可
            //         "approvalParams": "",
            
            if (node.nodeType === 2 || node.nodeType === 5) {
                let permiList=[]
                for (let btnPermissionKey in node.btnPermission) {
                    if (btnPermissionKey==='$$$component&&&'){
                        continue
                    }
                    permiList.push({
                        fieldId:btnPermissionKey,
                        permi:node.btnPermission[btnPermissionKey]
                    })
                }
                node.permiList=permiList;
                if (["1","4","6"].includes(node.approvalUserType)){
                    node.approvalParams=node.nodeApproveList.join(',')
                }else {
                    node.approvalParams=""
                }
                node.nodeProperty = node.approvalUserType;
                node.nodeDisplay=$func.setApproverStr(node)
                node.nodeObj=JSON.stringify({
                    btnPermission:node?.btnPermission,
                    vetoUsersList:node?.vetoUsersList,
                    nodeApproveList:node.nodeApproveList,
                })
                // 按钮权限
                delete node.nodeApproveList;
            }
        }
        return nodeList;
    }

}

